#include "StdAfx.h"
#include "p2psvrapp.h"

#include "./log/logmgr.h"
#include "./net/netmgr.h"
#include "./timer/timermgr.h"
#include "./protocol/P2PProtocolImpl.h"

INSTANCE_SINGLETON(CP2PSvrApp)

CP2PSvrApp::CP2PSvrApp(void)
{
}

CP2PSvrApp::~CP2PSvrApp(void)
{
}

bool CP2PSvrApp::Init( void )
{
    if (!CLogMgr::CreateInstance())
    {
        return false;
    }
    else
    {
        if (!CLogMgr::Instance()->Init())
        {
            return false;
        }
    }

    if (!CNetMgr::CreateInstance())
    {
        return false;
    }
    else
    {
        if (!CNetMgr::Instance()->Init())
        {
            return false;
        }
    }

    if (!CTimerMgr::CreateInstance())
    {
        return false;
    }
    else
    {
        if (!CTimerMgr::Instance()->Init())
        {
            return false;
        }
    }

    if (!CClientMgr::CreateInstance())
    {
        return false;
    }
    else
    {
        if (!CClientMgr::Instance()->Init())
        {
            return false;
        }
    }

    if (!CP2PProtocolImpl::CreateInstance())
    {
        return false;
    }

    return true;
}

void CP2PSvrApp::UnInit( void )
{
    if (CTimerMgr::Instance())
    {
        CTimerMgr::Instance()->UnInit();
        CTimerMgr::Instance()->DestoryInstance();
    }

    if (CNetMgr::Instance())
    {
        CNetMgr::Instance()->UnInit();
        CNetMgr::DestoryInstance();
    }

    if (CLogMgr::Instance())
    {
        CLogMgr::Instance()->UnInit();
        CLogMgr::DestoryInstance();
    }
}

bool CP2PSvrApp::Start( void )
{
    m_run = true;
    m_is_closing = false;
    return CThread::Start(false);
}

void CP2PSvrApp::Stop( void )
{
    m_is_closing = true;

    if (GetThreadId() != GetCurrentThreadId())
    {
        CThread::WaitFor();
    }
}

void CP2PSvrApp::ThreadProc( void )
{
    if (!Init())
    {
        UnInit();

        return;
    }

    LOG_CRI("p2p server start!");

    while (m_run)
    {
        bool busy = false;

        if (CNetMgr::Instance()->Run())
        {
            busy = true;
        }

        if (CTimerMgr::Instance()->Run())
        {
            busy = true;
        }

        if (!busy)
        {
            Sleep(1);
        }
    }

    UnInit();
}
